package com.axjy.service.impl;

import com.axjy.dao.HouseDao;
import com.axjy.pojo.House;
import com.axjy.service.HouseService;
import com.axjy.vo.HouseDto;
import com.axjy.vo.PageVo;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

@Service("houseService")
@Transactional
public class HouseServiceImpl extends BaseServiceImpl implements HouseService{

    @Resource
    private HouseDao houseDao;

    @Override
    public PageVo searchHouse(Integer offset, Integer pageSize, Integer userId) {
        Sort sort=Sort.by(Sort.Order.asc("id"));
        Pageable pageable= PageRequest.of(offset/pageSize,pageSize,sort);
        Page<House> page= houseDao.findByUserId(userId,pageable);
        PageVo pageVo=new PageVo();
        pageVo.setRows(page.getContent());
        pageVo.setTotal(page.getTotalElements());
        return pageVo;
    }

    @Override
    public PageVo searchHouseByDto(Integer offset, Integer pageSize, HouseDto dto) {
        StringBuffer sbf=new StringBuffer("select h from House h join fetch h.street s join fetch s.district d join fetch h.type t where 1=1");
        if(!StringUtils.isEmpty(dto.getTitle())){
            sbf.append(" and h.title=:title");
            dto.setTitle("%"+dto.getTitle()+"%");
        }
        if(dto.getStreetId()!=null){
            sbf.append(" and s.id=:streetId");
        }
        if(dto.getTypeId()!=null){
            sbf.append(" and t.id=:typeId");
        }
        if(dto.getStartPrice()!=null){
            sbf.append(" and h.price between :startPrice and h.endPrice");
        }
        String hql=sbf.toString();
        return super.searchPagination(hql,dto,offset,pageSize);
    }


}
